package com.panshi.hujin2.httpcrawler.util.outlook;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.panshi.hujin2.httpcrawler.domain.outlook.OutlookEmailItemInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * ItemIds转换工具
 * @Author: wangxl
 * @Date: 2018/11/21 18:57
 */
public class OutlookItemIdsParseUtil {

    private static Logger logger = LoggerFactory.getLogger(OutlookItemIdsParseUtil.class);

    /**
     * 解析findItem请求结果，获取所有邮件基础信息（主题，唯一ID）
     * @param responseContent
     * @return
     */
    public static List<OutlookEmailItemInfo> getItemIds(String responseContent){

        logger.info("解析收件箱内容");

        JsonParser jsonParser = new JsonParser();
        //转换json对象
        JsonObject jsonObject = jsonParser.parse(responseContent).getAsJsonObject();

        JsonObject responseMessages = jsonObject.getAsJsonObject("Body").getAsJsonObject("ResponseMessages");
        //当前session中邮件会话集合
        JsonArray itemsArray = responseMessages.getAsJsonArray("Items");

        JsonObject item = itemsArray.get(0).getAsJsonObject();

        JsonArray items = item.getAsJsonObject("RootFolder").getAsJsonArray("Items");

        List<OutlookEmailItemInfo> list = new ArrayList<OutlookEmailItemInfo>();
        OutlookEmailItemInfo info = null;
        for (JsonElement j:items){

            JsonObject temp = j.getAsJsonObject();
            // 有些情况下邮件没有主题
            if(temp.get("Subject")==null){
                continue;
            }
            //邮件主题
            String subject = temp.get("Subject").toString().replaceAll("\"","");

            //解析邮件时间 yyyy-MM-dd hh:mm:ss
            String receiveDate = getReceiveDate(temp.get("DateTimeReceived").toString());

            //邮件ID
            JsonObject ItemId = temp.getAsJsonObject("ItemId");
            String id = ItemId.get("Id").toString();

            //收件人邮件地址
            String senderName = temp.getAsJsonObject("Sender").getAsJsonObject("Mailbox").get("EmailAddress").toString().replaceAll("\"","");
            info = new OutlookEmailItemInfo(subject,id,null,senderName,receiveDate);
            list.add(info);
        }
        return list;
    }

    /**
     * 获取yyyy-MM-dd hh:mm:ss时间字符串
     * @param outlookEmailDateTime 微软提供的日期格式
     * @return
     */
    private static String getReceiveDate(String outlookEmailDateTime){
        String[] dateSplit = outlookEmailDateTime.toString().replaceAll("\"", "").split("T");
        String[] dateStr = dateSplit[0].split("-");
        String year = dateStr[0];
        String month = dateStr[1];
        if(month.length()==1){
            month="0"+month;
        }
        String day = dateStr[2];
        if(day.length()==1){
            day="0"+day;
        }
        String timeStr = dateSplit[1].replace("Z","").replace("z","");
        String[] timeStrSplit = timeStr.split(":");
        String hour = timeStrSplit[0];
        if(hour.length()==1){
            hour="0"+hour;
        }
        String min = timeStrSplit[1];
        if(min.length()==1){
            min="0"+min;
        }
        String sec = timeStrSplit[2];
        if(sec.length()==1){
            sec="0"+sec;
        }
        return year+"-"+month+"-"+day+" "+hour+":"+min+":"+sec;

    }
}
